package com.up.upzl.biz.controller;

import com.up.upzl.biz.bean.SysAccountInSession;
import com.up.upzl.biz.common.Constant;
import com.up.upzl.biz.domain.*;
import com.up.upzl.biz.domain.Shop.*;
import com.up.upzl.biz.service.*;

import org.apache.log4j.spi.LoggerFactory;
import org.slf4j.Logger;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.text.DecimalFormat;
import java.util.*;

/**
 * 商铺控制器
 * 
 * @author joker
 *
 */
@Controller
@RequestMapping("shop")
public class ShopController {
	@Autowired
	private ShopService shopService;
	@Autowired
	private ShopTagService shopTagService;
	@Autowired
	private ShopSupportingService shopSupportingService;
	@Autowired
	private ShopPaperService shopPaperService;
	@Autowired
	private ShopAdvantageService shopAdvantageService;
	@Autowired
	private ShopIssueService shopIssueService;
	@Autowired
	private ShopObstructService shopObstructService;
	@Autowired
	private ShopBlockService shopBlockService;
	@Autowired
	private ShopTransferService shopTransferService;
	@Autowired
	private SysAccountService sysAccountService;
	final Long initCount = 30000L;
	@Value("${up.site:}")
	private String site;

	private static final Logger log = org.slf4j.LoggerFactory.getLogger(ShopController.class);

	/**
	 * 跳转list页面
	 * 
	 * @return
	 */
	@GetMapping("list")
	public String list(CreateType createType, Long city, Long area, Long businessArea, Integer rentType, Type type,
			Long parentManageType, Long sonManageType, Integer onlineStatus, String name, String shopNumber,
			Date beginTime, Date endTime, Pageable page, Model model) {
		Page<Shop> list = shopService.findByCondition(createType, city, area, businessArea, rentType, type,
				parentManageType, sonManageType, onlineStatus, name, shopNumber, ShopAudit.审核已通过, beginTime, endTime,
				page);
		model.addAttribute("pageList", list);
		Integer openNumber = 0;
		Integer closeNumber = 0;
		List<Shop> lists = shopService.findAllX(createType, city, area, businessArea, rentType, type, parentManageType,
				sonManageType, onlineStatus, name, shopNumber, beginTime, endTime);

		for (Shop shop : lists) {
			if (!Objects.isNull(shop.getOnlineStatus()) && 1 == shop.getOnlineStatus()) {
				openNumber = openNumber + 1;
			} else {
				closeNumber = closeNumber + 1;
			}
		}
		model.addAttribute("openNumber", openNumber);
		model.addAttribute("closeNumber", closeNumber);

		return "shop/list";
	}

	/**
	 * 上线商铺（在app端显示）
	 * 
	 * @param id
	 *            商铺id
	 * @return true/false
	 */
	@PostMapping("onlineShop")
	public @ResponseBody Boolean onlineShop(Long id) {
		try {
			Shop shop = shopService.findOne(id);
			shop.setOnlineStatus(1);
			shopService.save(shop);
			return true;
		} catch (Exception e) {
			return false;
		}
	}

	/**
	 * 下线商铺（不在app端显示）
	 * 
	 * @param id
	 *            商铺id
	 * @return true/false
	 */
	@PostMapping("offlineShop")
	public @ResponseBody Boolean offlineShop(Long id) {
		try {
			Shop shop = shopService.findOne(id);
			shop.setOnlineStatus(0);
			shopService.save(shop);
			return true;
		} catch (Exception e) {
			return false;
		}
	}

	/**
	 * 跳转到添加页面
	 */
	@GetMapping("addPage")
	public String add(Model model) {
		this.initArrays(model);
		return "shop/add";
	}

	/**
	 * 保存对象
	 */
	@PostMapping("add")
	public @ResponseBody Map<String, String> save(@RequestBody Shop shop,
			@SessionAttribute(Constant.USER_IN_SESSION_KEY) SysAccountInSession session) {

		Shop shopByPhone = shopService.findByPhone(shop.getPhone());
		Map<String, String> map = new HashMap<>();
		if (Objects.isNull(shopByPhone)) {
			if (!StringUtils.isEmpty(site)) {
				site = site.toUpperCase().substring(0, 2);
			}
			StringBuffer name = new StringBuffer();
			if (shop.getArea() != null) {
				name.append(shop.getArea().getName());
			}
			if (shop.getBusinessArea() != null) {
				name.append(shop.getBusinessArea().getName());
			}
			if (shop.getRoad() != null) {
				name.append(shop.getRoad().getName());
			}
			if (shop.getUseArea() != null) {
				name.append(shop.getUseArea());
			}
			shop.setName(name.toString());
			shop.setCreateType(CreateType.后台录入);
			shop.setOnlineStatus(0);
			shop.setIsImport(1);
			Long shopCount = shopService.count();
			if (shopCount > 0) {
				Long newShopCount = shopCount + initCount;
				DecimalFormat df = new DecimalFormat("000000");
				String shopNumber = df.format(newShopCount);
				shop.setShopNumber(shopNumber);
				log.info("新生成商铺编号:{}", shopNumber);
			}
			// Long shopNumber = sequenceService.nextVal("sq_shopNumber");
			// shop.setShopNumber("0" + shopNumber);

			SysAccount checkUser = sysAccountService.findOne(session.getId());
			shop.setVerificationAccount(checkUser);
			shop.setShopAudit(ShopAudit.审核已通过);

			try {
				shopService.save(shop);
				map.put("Type", "200");
			} catch (Exception e) {
				map.put("Type", "500");
			}

		} else {
			map.put("Type", "300");
		}
		return map;
	}

	/**
	 * 跳转到更新页面
	 */
	@GetMapping("updatePage")
	public String update(Long id, Model model) {
		Shop shop = shopService.findOne(id);
		this.initArrays(model);
		model.addAttribute("entity", shop);
		return "shop/update";
	}

	/**
	 * 跳转到详情页面
	 */
	@GetMapping("detail")
	public String detail(Long id, Model model) {
		Shop shop = shopService.findOne(id);
		this.initArrays(model);
		model.addAttribute("entity", shop);
		return "shop/detail";
	}

	
	
	/**
	 * 更新商铺管理
	 */
	@GetMapping("validShopByPhone")
	public @ResponseBody boolean validShopPhone(String phone,String shopId) {
		Shop shopByPhone=shopService.findByPhone(phone);
		if(StringUtils.isEmpty(shopId)) {
			return Objects.isNull(shopByPhone);	
		}else {
			if(null==shopByPhone) {
				return true;
			}else {
				return shopId.equals(shopByPhone.getId().toString());
			}
		}
		
	}

	
	
	/**
	 * 更新商铺管理
	 */
	@PostMapping("shopupdate")
	public @ResponseBody Map<String, String> shopupdate(@RequestBody Shop shop) {
		Assert.notNull(shop.getId(), "Id can`t be null");
		Shop shopInDB = shopService.findOne(shop.getId());
		BeanUtils.copyProperties(shop, shopInDB, "status", "onlineStatus", "shopNumber", "createType",
				"verificationAccount", "shopFlow");
		// shopInDB.setStatus(shop.getStatus());
		// shopInDB.setFit(shop.getFit());
		// shopInDB.setSignageFacade(shop.getSignageFacade());
		// shopInDB.setSignagePlane(shop.getSignagePlane());
		// shopInDB.setShopObstructs(shop.getShopObstructs());
		// shopInDB.setTurnoverUnit(shop.getTurnoverUnit());
		shopInDB.setOnlineStatus(0);
		Shop shopByPhone = shopService.findByPhone(shop.getPhone());
		Map<String, String> map = new HashMap<>();
		if (Objects.isNull(shopByPhone)||(Objects.nonNull(shopByPhone)&&shopByPhone.getId()==shopInDB.getId())) {
			StringBuffer name = new StringBuffer();
			// if(SubmitStatus.提交审核.equals(shopInDB.getSubmitStatus())) {
			// shopInDB.setShopFlow(ShopFlow.待审核);
			shopInDB.setShopAudit(ShopAudit.审核已通过);
			// shopInDB.setShopFlow(ShopFlow.);
			// }
			shopInDB.setIsImport(1);
			if (shop.getArea() != null) {
				name.append(shop.getArea().getName());
			}
			if (shop.getBusinessArea() != null) {
				name.append(shop.getBusinessArea().getName());
			}
			if (shop.getArea() != null) {
				name.append(shop.getRoad().getName());
			}
			if (shop.getRoad() != null) {
				name.append(shop.getRoad().getName());
			}
			if (shop.getUseArea() != null) {
				name.append(shop.getUseArea());
			}
			shopInDB.setName(name.toString());

			try {
				shopService.save(shopInDB);
				map.put("Type", "200");
			} catch (Exception e) {
				map.put("Type", "500");
			}
		} else {
			map.put("Type", "300");
		}
		return map;
	}

	/**
	 * 核实核铺
	 */
	@PostMapping("update")
	public @ResponseBody Map<String, String> update(@RequestBody Shop shop,
			@SessionAttribute(Constant.USER_IN_SESSION_KEY) SysAccountInSession session) {
		Assert.notNull(shop.getId(), "Id can`t be null");

		Shop shopInDB = shopService.findOne(shop.getId());
		// BeanUtils.copyProperties(shop, shopInDB, "status", "onlineStatus",
		// "shopNumber", "createType",
		// "verificationAccount","shopFlow");
		// onlineStatus 上架状态（0 下架 1 上架）
		// shopNumber 商铺编号
		// createType 商铺来源
		// verificationAccount 核实人账号

		// 商铺租售状态（0：租赁中，1：已成交，2：已租出一部分，3：停转/租-违建拆除，4：停转/租-房东收回，5：停转/租-被查封，6：停转/租-继续经营）
		// shopInDB.setStatus(shop.getStatus());
		// 装修情况(0:精装,1:简装,2:毛坯/清水房)

		// shopInDB.setFit(shop.getFit());
		// 商铺店招(复选)(立面店招)
		// shopInDB.setSignageFacade(shop.getSignageFacade());
		// 商铺店招(复选)(平面店招)
		// shopInDB.setSignagePlane(shop.getSignagePlane());
		// 店前阻隔
		// shopInDB.setShopObstructs(shop.getShopObstructs());
		// 营业额单位
		// shopInDB.setTurnoverUnit(shop.getTurnoverUnit());
		// 进入待审核列表
		if (SubmitStatus.提交审核 == shop.getSubmitStatus() || SubmitStatus.核铺待维护 == shop.getSubmitStatus()) {
			BeanUtils.copyProperties(shop, shopInDB, "onlineStatus", "shopNumber", "createType", "userCode",
					"claimTime");
			// 商铺名称重新设置
			StringBuffer name = new StringBuffer();
			if (shop.getArea() != null) {
				name.append(shop.getArea().getName());
			}
			if (shop.getBusinessArea() != null) {
				name.append(shop.getBusinessArea().getName());
			}
			if (shop.getRoad() != null) {
				name.append(shop.getRoad().getName());
			}
			if (shop.getUseArea() != null) {
				name.append(shop.getUseArea());
			}
			shopInDB.setName(name.toString());
			if (SubmitStatus.提交审核 == shop.getSubmitStatus()) {
				shopInDB.setShopAudit(ShopAudit.待审核);
				// 停留在待核实列表
			} else if (SubmitStatus.核铺待维护 == shop.getSubmitStatus()) {
				shopInDB.setShopFlow(ShopFlow.核铺待维护);
			}
		} else if (SubmitStatus.核实无效 == shop.getSubmitStatus()) {
			shopInDB.setSubmitStatus(SubmitStatus.核实无效);
			shopInDB.setShopFlow(ShopFlow.核铺无效);
		}

		// 审核人，审核时间
		SysAccount sysAccount = sysAccountService.findOne(session.getId());
		shopInDB.setVerificationAccount(sysAccount);
		shopInDB.setVerifyTime(new Date());// 核实时间及审核里边的提交时间

		Map<String, String> map = new HashMap<>();
		try {
			shopService.save(shopInDB);
			map.put("Type", "200");
		} catch (Exception e) {
			map.put("Type", "500");
		}
		return map;
	}

	public void initArrays(Model model) {
		List<ShopTag> shopTags = shopTagService.findAll(new Sort(Direction.DESC, "sort"));
		List<ShopSupporting> shopSupportings = shopSupportingService.findAll(new Sort(Direction.DESC, "sort"));
		List<ShopPaper> shopPapers = shopPaperService.findAll(new Sort(Direction.DESC, "sort"));
		List<ShopAdvantage> shopAdvantages = shopAdvantageService.findAll(new Sort(Direction.DESC, "sort"));
		List<ShopIssue> shopIssues = shopIssueService.findAll(new Sort(Direction.DESC, "sort"));
		List<ShopObstruct> shopObstructs = shopObstructService.findAll(new Sort(Direction.DESC, "sort"));
		List<ShopBlock> shopBlocks = shopBlockService.findAll(new Sort(Direction.DESC, "sort"));
		List<ShopTransfer> shopTransfers = shopTransferService.findAll(new Sort(Direction.DESC, "sort"));

		model.addAttribute("shopTags", shopTags);
		model.addAttribute("shopSupportings", shopSupportings);
		model.addAttribute("shopPapers", shopPapers);
		model.addAttribute("shopAdvantages", shopAdvantages);
		model.addAttribute("shopIssues", shopIssues);
		model.addAttribute("shopObstructs", shopObstructs);
		model.addAttribute("shopBlocks", shopBlocks);
		model.addAttribute("shopTransfers", shopTransfers);
	}
}
